package com.example.mq1.common;

import com.example.mq1.mqserver.core.Message;

import java.io.*;

public class BinaryTool {

    /**
     * 将消息序列化成二进制数组
     * @return
     */
    public static byte[] toBytes(Object object) throws IOException {
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
            try(ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {
                objectOutputStream.writeObject(object);
            }
            return byteArrayOutputStream.toByteArray();
        }
    }

    /**
     * 将二进制数据序列化成消息
     * @param arr
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static Object fromBytes(byte[] arr) throws IOException, ClassNotFoundException {
        Object object = null;
        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(arr)) {
            try (ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)) {
                object = objectInputStream.readObject();
            }
        }
        return object;
    }

}
